<template>
  <!-- 地区级联选择器组件 -->
  <div v-if="state.isShow">
    <el-cascader
      class="cascader"
      size="small"
      @focus="clearChoose"
      @change="changeEvent"
      :props="loadAreaProps"
      v-model="state.queryAreaInfo"
      :options="state.provinceOps"
    ></el-cascader>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, watch } from "vue";
import { getAllProvince, getProById } from '@/api/Area/area';

export interface pro {    //省份对象
  value: string,
  label: string,
  id: string,
}
export default defineComponent({
  //地区级联组件
  name: 'UecpVue3Regionalleague',
  props: {
    cityId: {
      type: String,
    },
    provinceName: {
      type: String,
    },
    cityName: {
      type: String
    }
  },
  setup(props, { emit }) {

    const state = reactive({
      provinceOps: [] as pro[],
      queryAreaInfo: ['', ''],
      targetProList: [],
      isShow: true
    })

    watch(props, (newProps: any, oldProps) => {
      if (newProps.provinceName && newProps.cityName) {
        state.queryAreaInfo[0] = newProps.provinceName
        state.queryAreaInfo[1] = newProps.cityName
      }
    }, { immediate: true, deep: true })

    const loadAreaProps = reactive({
      lazy: true,
      async lazyLoad(node: any, resolve: any) {
        const { level } = node
        const res: any = await getProById(node.data.id || 1)
        state.targetProList = res.data.cities
        const nodes = res.data.cities.map((e: any) => {
          let obj = {
            id: e.id,
            value: e.name,
            label: e.name,
            leaf: level >= 1,
          }
          return obj
        })
        resolve(nodes)
      }
    })

    const getProvinceInfo = async (): Promise<void> => {
      const res: any = await getAllProvince()
      if (res.data.ret === 0) {
        state.provinceOps = res.data.provs.map((e: any) => {
          let obj = {
            id: e.id,
            value: e.name,
            label: e.name
          }
          return obj
        })
      }
      // console.log(state.provinceOps)
    }

    getProvinceInfo()

    const clearChoose = () => {
      state.queryAreaInfo = []
    }

    const changeEvent = () => {
      let cityInfo = state.targetProList.find((e: any) => {
        return e.name === state.queryAreaInfo[1]
      })
      emit('areaChange', state.queryAreaInfo, cityInfo)
    }

    return {
      state,
      loadAreaProps,
      changeEvent,
      clearChoose,
    }
  }
})
</script>

<style lang="scss" scoped>
.el-cascader-menu {
  height: 300px;
}

:deep(.cascader) .el-input__suffix {
  right: 55px;
}
</style>